import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-12
 * Time: 8:04
 */
class Solution3 {
    public int findKthLargest(int[] nums, int k) {
        return qsort(nums,0,nums.length-1,k);
    }

    public int qsort(int[] nums,int l,int r,int k) {
        if(l == r) {
            return nums[l];
        }

        int left = l-1, right = r+1, i = l;
        int key = nums[new Random().nextInt(r-l+1)+l];

        while(i < right) {
            if(nums[i] < key) {
                swap(nums,++left,i++);
            }else if(key == nums[i]) {
                i++;
            }else {
                swap(nums,--right,i);
            }
        }

        int a = r-right+1, b = right- left - 1;

        if(a >= k) {
            return qsort(nums,right,r,k);
        }else if(a+b >= k) {
            return key;
        }else {
            return qsort(nums,l,left,k-a-b);
        }
    }

    public void swap(int[] nums,int i,int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
